<template>
  <a-modal :width="600" @cancel="emits('cancel')" v-model:visible="visible" title="创建优惠券">
    <a-form ref="formRef" name="custom-validation" :model="formState" :rules="rules" :label-col="{ span: 4 }" :wrapper-col="{ span: 16 }">
      <a-form-item label="类型" name="c_type">
        <a-select v-model:value="formState.c_type">
          <a-select-option :value="1">微信公众号赠送</a-select-option>
          <a-select-option :value="2">抖音视频赠</a-select-option>
          <a-select-option :value="3">用户购买</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="金额" name="amount">
        <a-input-number class=" !w-[50%]" v-model:value="formState.amount" :min="0" placeholder="请输入金额(单位分)" />
        <span>（单位分，1元请填写100）</span>
      </a-form-item>
      <a-form-item label="tokens次数" name="tokens">
        <a-input-number class=" !w-full" :precision="0" v-model:value="formState.tokens" :min="0" placeholder="请输入tokens次数" />
      </a-form-item>
      <a-form-item label="创建张数" name="quantity">
        <a-input-number class=" !w-full" :precision="0" v-model:value="formState.quantity" :min="0" placeholder="请输入创建张数" />
      </a-form-item>
      <a-form-item label="备注" name="remark">
        <a-textarea v-model:value="formState.remark" placeholder="请输入备注" auto-size />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button key="back" @click="emits('cancel')">取消</a-button>
      <a-button class=" bg-base text-white" key="submit" type="primary" @click="submit">提交</a-button>
    </template>
  </a-modal>
</template>

<script lang='ts' setup>
import { createCoupons } from '@/request/api'
import type { create_coupons } from '@/types/coupons'
import { message } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
const emits = defineEmits(['cancel', 'getData'])
const formRef = ref<any>()
let visible = ref<boolean>(false)
const props = withDefaults(
  defineProps<{
    show: boolean
  }>(),
  {
    show: false,
  }
)
watch(
  () => props.show,
  (newVal) => {
    visible.value = JSON.parse(JSON.stringify(props.show))
    if (!props.show) {
      nextTick(() => {
        formRef.value.resetFields()
      })
    }
  }
)

const rules: Record<string, Rule[]> = {
  amount: [{ required: true, message: '此项必填', trigger: 'change' }],
  c_type: [{ required: true, message: '此项必填', trigger: 'change' }],
  quantity: [{ required: true, message: '此项必填', trigger: 'change' }],
  remark: [{ required: true, message: '此项必填', trigger: 'change' }],
  tokens: [{ required: true, message: '此项必填', trigger: 'change' }],
}
const formState = reactive<create_coupons>({
  amount: 0,
  c_type: 1,
  quantity: 0,
  remark: '',
  tokens: 0,
})
const submit = () => {
  formRef.value.validate().then(() => {
    createCoupons({
      ...formState,
    }).then((res) => {
      if (res.code == 200) {
        message.success('创建成功！')
        emits('getData')
        emits('cancel')
      }
    })
  })
}
</script>